import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
import axios from "axios";

import vuexPer from "vuex-persistedstate";
export default new Vuex.Store({
  state: {
    // name: "小明",
    list: [],
  },
  getters: {},
  mutations: {
    // change(state) {
    //   state.name = "xiaoli";
    // },
    setData(state, val) {
      state.list = val;
    },
    //操作list 只能通过mutation操作

    add(state, id) {
      // state.list[index].count++;
      //这里不适合用下标 而适合用id
      state.list.forEach((i) => {
        if (i.id == id) {
          i.count++;
        }
      });
    },
    plus(state, id) {
      // state.list[index].count--;
      state.list.forEach((i) => {
        if (i.id == id) {
          i.count--;
        }
      });
    },
    remove(state, id) {
      state.list.forEach((i) => {
        if (i.id == id) {
          i.count = 0;
        }
      });
    },
  },
  actions: {
    // setChange(context) {
    //   context.commit("change");
    // },
    // context代表整个仓库 可以直接调用mutations修改state 但是按照运行机制来说 需要先调用一个actions 再调用 mutation 修改state

    getData(ctx) {
      axios.get("data.json").then((res) => {
        console.log(res);
        ctx.commit("setData", res.data.productsData);
      });
    },
    //发送异步请求放在actions下发送
  },
  modules: {},
  plugins: [vuexPer()],
});
